package com.hippo.core.util;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * 反射调用浏览器方法
 * @author hippo
 */
@Slf4j
public class InvokeFunction {

    /**
     * 反射调用方法
     *
     * @param instance  实例
     * @param func      方法名
     * @param arrayList el+data合并的数组
     * @param stepName  步骤名称
     * @return success或错误日志
     */
    public String runInstanceFunction(Object instance, String func, JSONArray arrayList, String stepName) {
        int size = arrayList.size();
        try {
            Object invoke;
            if (size > 0) {
                Object[] paramList = new Object[size];
                Class[] classList = new Class[size];
                for (int i = 0; i < size; i++) {
                    classList[i] = arrayList.get(i).getClass();
                    paramList[i] = arrayList.get(i);
                }
                Method method = instance.getClass().getMethod(func, classList);
                invoke = method.invoke(instance, paramList);
            } else {
                Method method = instance.getClass().getMethod(func);
                invoke = method.invoke(instance);
            }
            log.info("成功执行：" + stepName);
            if (func.equals("execScreenshot")) {
                return invoke.toString();
            } else {
                return "success";
            }
        } catch (Exception e) {
//            e.printStackTrace();
            Throwable cause = e.getCause();
            log.error("失败执行：" + stepName);
            log.error(cause.toString());
            return cause.toString();
        }
    }
}